﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using InfoPick.Lib.Telnet;
using Telerik.Windows.Controls;
using InfoPick.Lib.StringResolve;
using InfoPick.Lib;
using InfoPick.Lib.Entity;
using InfoPick.Lib.Tools;
using InfoPick.UI.Comm;
using System.Windows.Forms;
using InfoPick.Lib.Service;
using InfoPick.Lib.DataPicker;
using System.Collections.Specialized;
using InfoPick.UI.ViewModel;
using System.IO;
using System.Configuration;
using InfoPick.Lib.Log;
using System.Collections;

namespace InfoPick.UI.Views
{
    /// <summary>
    /// Interaction logic for InfoPickPage.xaml
    /// </summary>
    public partial class InfoPickPage : Page
    {
        private Thread t = null;
        string debug = ConfigurationManager.AppSettings["Debug"];
        public InfoPickPage()
        {
            InitializeComponent();

            
            if (debug == "true")
            {
                tab4.Visibility = tab5.Visibility = tab6.Visibility = Visibility.Visible;
            }
            else
            {
                tab4.Visibility = tab5.Visibility = tab6.Visibility = Visibility.Collapsed;
            }

            //生成测试数据
            //generateTestData();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            ServerService ser1 = new ServerService("MGWS");
            string defaultSer1 = string.Empty;
            var list1 = ser1.LoadList(ref defaultSer1);
            cboxMGW.ItemsSource = list1;
            if (!string.IsNullOrEmpty(defaultSer1))
            {
                var obj = list1.SingleOrDefault(c => c.Guid.ToString() == defaultSer1);
                if (obj != null)
                    cboxMGW.SelectedItem = obj;
            }

            ServerService ser2 = new ServerService("MSCS");
            string defaultSer2 = string.Empty;
            var list2 = ser2.LoadList(ref defaultSer2);
            cboxMSC.ItemsSource = list2;
            if (!string.IsNullOrEmpty(defaultSer2))
            {
                var obj = list2.SingleOrDefault(c => c.Guid.ToString() == defaultSer2);
                if (obj != null)
                    cboxMSC.SelectedItem = obj;
            }

            PathService ser3 = new PathService();
            tbMGW.Text = ser3.GetMGWPath();
            tbMSC.Text = ser3.GetMSCPath();
            tbExcelPath.Text = ser3.GetLastExcelPath();
            initTabText();
        }

        List<CmdResModel> crList = new List<CmdResModel>();

        void GetData(string mgwPath,string mscPath,string excelFullPath,Server mgw = null,Server msc = null)
        {
            Action<string> onNotice = new Action<string>((msg) =>
            {
                Dispatcher.Invoke(new Action(() => { rtb.AppendText(msg); }), null);
            });

            Action<string, string> onCmdSuccess = new Action<string, string>((cmd, res) =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                    {
                        var obj = new CmdResModel { Cmd = cmd, Res = res };
                        lb.Items.Add(obj);
                        if (lb.Items.Count > 0)
                            lb.ScrollIntoView(lb.Items[lb.Items.Count - 1]);
                        crList.Add(obj);
                    }), null
                );
            });

            DataPicker df = new DataPicker(onNotice, onCmdSuccess);
            try
            {
                var data = df.Start(mgw, msc,excelFullPath, mgwPath, mscPath);
                if (data != null)
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                                    {
                                        grid1.ItemsSource = data.GMDDFListExcel;
                                        grid2.ItemsSource = data.GSDDFListExcel;
                                        grid3.ItemsSource = data.GMODFListExcel;
                                        if (debug == "true")
                                        {
                                            grid4.ItemsSource = data.GMDDFListProgram;
                                            grid5.ItemsSource = data.GSDDFListProgram;
                                            grid6.ItemsSource = data.GMODFListProgram;
                                        }
                                    }), null);
                }
            }
            catch (Exception ex)
            {
                onNotice(string.Format("发生错误 {0}\n", ex.Message));
                string message = string.Format("{0} : message:{1}\r\n{2}", DateTime.Now, ex.Message, ex.StackTrace);
                Log.WriteLog(message);
            }
            finally
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    btnStart.IsEnabled = true;
                }), null);
                
            }
            
        }

        private void lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems != null && e.AddedItems.Count > 0)
            {
                var obj = e.AddedItems[0] as CmdResModel;

                tbDetail.Text = obj.Res;
            }
        }

        private void Tab1_SelectionChanged(object sender, RadSelectionChangedEventArgs e)
        {

        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
           
            if (btnOnline.IsChecked==true)
            {
                Server mgw = cboxMGW.SelectedItem as Server;
                Server msc = cboxMSC.SelectedItem as Server;
                if (mgw == null || msc == null)
                {
                    Tools.ShowMessage(false, "请选择服务器！");
                    return;
                }
                string excelFullPaht = tbExcelPath.Text.Trim();
                if (!File.Exists(excelFullPaht))
                {
                    Tools.ShowMessage(false, "‘原始excel’文件不存在，请重新选择！");
                    return;
                }

                //设置默认参数
                ServerService ser1 = new ServerService("MGWS");
                ser1.SetDefault(mgw);
                ServerService ser2 = new ServerService("MSCS");
                ser2.SetDefault(msc);
                PathService ser3 = new PathService();
                ser3.SetExcelPath(excelFullPaht);

                t = new Thread(new ThreadStart(() => { GetData("", "", excelFullPaht, mgw, msc); }));
                
            }
            if (btnOffline.IsChecked == true)
            {
                string mgwPath = tbMGW.Text.Trim();
                if (!File.Exists(mgwPath))
                {
                    Tools.ShowMessage(false, "‘MGW文件’不存在，请重新选择！");
                    return;
                }
                string mscPath = tbMSC.Text.Trim();
                if (!File.Exists(mscPath))
                {
                    Tools.ShowMessage(false, "‘MSC文件’不存在，请重新选择！");
                    return;
                }
                string excelFullPath = tbExcelPath.Text.Trim();
                if (!File.Exists(excelFullPath))
                {
                    Tools.ShowMessage(false, "‘原始excel’文件不存在，请重新选择！");
                    return;
                }

                //设置默认参数
                PathService ser3 = new PathService();
                ser3.SetMGWPath(mgwPath);
                ser3.SetMSCPath(mscPath);
                ser3.SetExcelPath(excelFullPath);

                t = new Thread(new ThreadStart(() => { GetData(mgwPath, mscPath, excelFullPath); }));
                
            }

            if (t != null)
            {
                t.IsBackground = true;
                btnStart.IsEnabled = false;
                clear();
                t.Start();
            }
        }

        private void clear()
        {
            if (grid1.ItemsSource is IList)
            {
                (grid1.ItemsSource as IList).Clear();
                grid1.ItemsSource = null;
            }
            if (grid2.ItemsSource is IList)
            {
                (grid2.ItemsSource as IList).Clear();
                grid2.ItemsSource = null;
            }
            if (grid3.ItemsSource is IList)
            {
                (grid3.ItemsSource as IList).Clear();
                grid3.ItemsSource = null;
            }
            if (grid4.ItemsSource is IList)
            {
                (grid4.ItemsSource as IList).Clear();
                grid4.ItemsSource = null;
            }
            if (grid5.ItemsSource is IList)
            {
                (grid5.ItemsSource as IList).Clear();
                grid5.ItemsSource = null;
            }
            if (grid6.ItemsSource is IList)
            {
                (grid6.ItemsSource as IList).Clear();
                grid6.ItemsSource = null;
            }

            rtb.Document.Blocks.Clear();
            lb.Items.Clear();
            tbDetail.Clear();
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            if (t.ThreadState != ThreadState.Stopped)
                t.Abort();

        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            List<GMDDF> ddfList = grid1.ItemsSource as List<GMDDF>;
            List<GMODF> odfList = grid3.ItemsSource as List<GMODF>;
            List<GSDDF> gsList = grid2.ItemsSource as List<GSDDF>;
            if (ddfList == null)
                ddfList = new List<GMDDF>();
            if (odfList == null)
                odfList = new List<GMODF>();
            if (gsList == null)
                gsList = new List<GSDDF>();
            if (ddfList.Count == 0 && odfList.Count == 0 && gsList.Count == 0)
            {
                Tools.ShowMessage(false, "没有数据！");
                return;
            }

            SaveFileDialog dialog = new SaveFileDialog();
            string extension = "xls";
            string SelectedExportFormat = "excel";
            dialog.DefaultExt = extension;
            dialog.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, SelectedExportFormat);
            dialog.FilterIndex = 1;

            var res = dialog.ShowDialog();
            if (res == DialogResult.OK)
            {
                string[] sheetNames = new string[] { tab1.Text, tab2.Text, tab3.Text };
                ExcelTools.Export(dialog.FileName, ddfList, odfList, gsList, sheetNames);
                if (debug == "true")
                {
                    var ddfListP = grid4.ItemsSource as List<GMDDF>;
                    var gsListP = grid5.ItemsSource as List<GSDDF>;
                    var odfListP = grid6.ItemsSource as List<GMODF>;

                    FileInfo fi = new FileInfo(dialog.FileName);
                    string fileName = string.Format("{0}\\{1}{2}", fi.Directory, fi.Name.Replace(fi.Extension,"") + "程序获取", fi.Extension);
                    ExcelTools.Export(fileName, ddfListP, odfListP, gsListP, sheetNames);
                }
                Tools.ShowMessage(true, "导出成功");
            }
           

        }

        /// <summary>
        /// 生成测试数据
        /// </summary>
        private void generateTestData()
        {
            const int len = 1000;
            {
                List<GMDDF> ddfList = new List<GMDDF>();
                for (int i = 0; i < len; i++)
                {
                    GMDDF obj = new GMDDF();
                    obj.Id = i + 1;
                    obj.Name = "主控机柜";
                    obj.Frame = 1;
                    obj.BoardNum = 2;
                    obj.SLotNum = 3;
                    obj.Port = i;
                    obj.GlobalNum = 0;
                    obj.GlobalTid = 4;
                    obj.No7Link = "TS1-31";
                    obj.GroupNum = "DDF2-1-1";
                    obj.System = i;
                    obj.Direction = "CQGM241-B1";
                    obj.Remark = "提取线路时钟";
                    obj.BSGNum = 5;
                    obj.SPFNum = 6;
                    obj.KNum = 0;
                    obj.CCUNum = 7;
                    obj.SCNum = 1;
                    obj.ECNum = 31;
                    obj.StartCic = 32;
                    obj.StartTid = i + 1;

                    ddfList.Add(obj);
                }

                grid1.ItemsSource = ddfList;
            }
            {
                List<GMODF> odfList = new List<GMODF>();
                for (int i = 0; i < len; i++)
                {
                    GMODF obj = new GMODF();
                    obj.Id = i + 1;
                    obj.Name = "主控机柜";
                    obj.Frame = 1;
                    obj.BoardNum = 2;
                    obj.SLotNum = 3;
                    obj.IsPrimary = true;
                    obj.Port = i;
                    obj.GlobalNum = 0;
                    obj.GlobalTid = 4;
                    obj.ODFPosition = "ODF Position";
                    obj.No7Link = "TS1-31";
                    obj.System = i;
                    obj.Direction = "CQGM241-B1";
                    obj.Remark = "提取线路时钟";
                    obj.SPFNum = 6;
                    obj.KNum = 0;
                    obj.CCUNum = 7;
                    obj.SCNum = 1;
                    obj.ECNum = 31;
                    obj.StartCic = 32;
                    obj.StartTid = i + 1;

                    odfList.Add(obj);
                }

                grid3.ItemsSource = odfList;
            }
            {
                List<GSDDF> gsList = new List<GSDDF>();
                for (int i = 0; i < len; i++)
                {
                    GSDDF obj = new GSDDF();
                    obj.Id = i + 1;
                    obj.Name = "主控机柜";
                    obj.Frame = 1;
                    obj.SLotNum = 3;
                    obj.Port = i;
                    obj.LinkType = "2M";
                    obj.No7Link = "TS1-31";
                    obj.GroupNum = "4";
                    obj.Direction = "CQGM241-B1";

                    obj.Remark = "提取线路时钟";
                    obj.CSUNum = 5;

                    gsList.Add(obj);
                }

                grid2.ItemsSource = gsList;
            }
        }

        private void tbMGW_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            string extension = "txt";
            string SelectedExportFormat = "txt";
            dlg.DefaultExt = extension;
            dlg.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, SelectedExportFormat);
            dlg.FilterIndex = 1;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                tbMGW.Text = dlg.FileName;
            }
        }

        private void tbMSC_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            string extension = "txt";
            string SelectedExportFormat = "txt";
            dlg.DefaultExt = extension;
            dlg.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, SelectedExportFormat);
            dlg.FilterIndex = 1;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                tbMSC.Text = dlg.FileName;
            }
        }


        private void RadRadioButton_Click(object sender, RoutedEventArgs e)
        {
            RadRadioButton btn = sender as RadRadioButton;
            if (btn != null)
            {
                if (btn.Content.ToString() == "在线")
                {
                    cbMGWPanel.Visibility = cbMSCPanel.Visibility = Visibility.Visible;
                    tbMGWPanel.Visibility = tbMSCPanel.Visibility = Visibility.Collapsed;
                }
                if (btn.Content.ToString() == "离线")
                {
                    cbMGWPanel.Visibility = cbMSCPanel.Visibility = Visibility.Collapsed;
                    tbMGWPanel.Visibility = tbMSCPanel.Visibility = Visibility.Visible;
                }
            }
        }

        private void btnStart_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            btnStop.IsEnabled = !btnStart.IsEnabled;
            btnExport.IsEnabled = btnStart.IsEnabled;
        }

        private void tbExcelPath_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            string extension = "xls";
            string SelectedExportFormat = "excel";
            dlg.DefaultExt = extension;
            dlg.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, SelectedExportFormat);
            dlg.FilterIndex = 1;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                tbExcelPath.Text = dlg.FileName;
            }

            initTabText();
        }

        private void initTabText()
        {
            if (string.IsNullOrEmpty(tbExcelPath.Text.Trim()))
                return;
            try
            {
                tab1.Text = "CQGM-DDF电口";
                tab2.Text = "CQGS-DDF电口";
                tab3.Text = "CQGM-ODF光口";

                FileInfo fi = new FileInfo(tbExcelPath.Text);
                string file = fi.Name;
                int sep = file.IndexOf("端口");
                if (sep != -1)
                {
                    string sub = file.Substring(0, sep);
                    string splitKey = string.Empty;
                    
                    if (sub.Contains("_"))
                        splitKey = "_";
                    else if (sub.Contains("-"))
                        splitKey = "-";
                    else if (sub.Contains(" "))
                        splitKey = " ";
                    if (!string.IsNullOrEmpty(sub))
                    {
                        var ary = sub.Split(splitKey.ToArray(),StringSplitOptions.RemoveEmptyEntries);
                        if (ary.Length == 2)
                        {
                            tab1.Text = string.Format("{0}-DDF电口", ary[1]);
                            tab2.Text = string.Format("{0}-DDF电口", ary[0]);
                            tab3.Text = string.Format("{0}-ODF光口", ary[1]);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("{0} : message:{1}\r\n{2}", DateTime.Now, ex.Message, ex.StackTrace);
                Log.WriteLog(message);
            }
        }

        private void tb_TextChanged(object sender, TextChangedEventArgs e)
        {
            rtb.ScrollToEnd();
        }

        
       
    }
}
